/** 
 * @Title:  OrderController.java 
 * @author:  xuron
 * @data:  2015年11月27日 下午2:57:17 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月27日 下午2:57:17 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月27日 下午2:57:17 <修改时间>
 * @log: <修改内容>
 */
package com.woyou.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.woyou.activity.HomeActivity;
import com.woyou.bean.FmInfo;
import com.woyou.bean.Order;
import com.woyou.bean.WYList;
import com.woyou.bean.rpc.QueryOrderDetailsReq;
import com.woyou.bean.rpc.QueryOrderDetailsRes;
import com.woyou.bean.rpc.QueryOrderReq;
import com.woyou.bean.rpc.QueryOrderRes;
import com.woyou.bean.rpc.Result;
import com.woyou.fragment.MessageFragment;
import com.woyou.fragment.SoldoutFragment;
import com.woyou.fragment.analysis.ReportFragment;
import com.woyou.fragment.order.OrderDetailsFragment;
import com.woyou.fragment.order.OrderFragment;
import com.woyou.model.OrderManageModel;
import com.woyou.model.rpc.OrderModel;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;

import android.content.Context;
import android.view.View;
import retrofit.RetrofitError;

/**
 * 抽离OrderFragment的逻辑到OrderController中
 * 
 * @author xuron
 * @versionCode 1 <每次修改提交前+1>
 */
public class OrderController extends SuperController {
	private HomeActivity homeActivity;
	private OrderModel orderModel;
	private OrderManageModel omModel = OrderManageModel.getInstance();
	private OrderFragment orderFragment;
	/**
	 * 定时刷新本地订单timer
	 */
	private Timer refreshTimer;
	private TimerTask refreshTimerTask;
	public QueryOrderDetailsRes queryOrderDetailsRes;
	
	/**
	 * @param mContext
	 */
	public OrderController(Context mContext) {
		super(mContext);
		homeActivity=(HomeActivity)mContext;
		orderModel = OrderModel.getInstance(homeActivity);
		orderFragment=homeActivity.getOrderFm();
	}

	/**
	 * 先获取订单详情再跳转到订单详情页面
	 */
	public void jumpToOrderDetails(final int position, final WYList<HashMap<String, String>> orderList) {
		homeActivity.hideInputMethod();
		ThreadPoolManager.getInstance().executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryOrderDetailsReq queryOrderDetailsReq = new QueryOrderDetailsReq();
					queryOrderDetailsReq.setoId(orderList.get(position).get("No"));
					queryOrderDetailsReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryOrderDetailsReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					Result<QueryOrderDetailsRes> result = orderModel.v2_3queryOrderDetails(queryOrderDetailsReq);
					if (result != null && result.getCode() == 1) {
						queryOrderDetailsRes = result.getData();
						// 将目标订单详情放入缓存中
						aCache.put("orderDetail", queryOrderDetailsRes);
						homeActivity.openFM(new FmInfo(OrderDetailsFragment.class, null, false));
					} else if (result != null && result.getCode() == -3) {
						homeActivity.homeController.exitLogin();
					}
				} catch (RetrofitError error) {
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});

	}
	/**
	 * 跳转到暂缺商品
	 */
	public void jump2SoldoutFragment() {
		homeActivity.openSubFM(homeActivity.getOrderFm(), new FmInfo(SoldoutFragment.class,"暂缺商品", false));
	}

	/**
	 * 跳转到评论列表
	 */
	public void jump2MessageFragment() {
		homeActivity.openSubFM(homeActivity.getOrderFm(), new FmInfo(MessageFragment.class,"消息中心", false));
	}

	/**
	 * 跳转到营业报表
	 */
	public void jump2ReportFragment() {

		// 判断是否在5分钟内的解锁期内
		if (!homeActivity.isUnlock5Minute) {
			// 判断是否设置了老板锁
			if (aCache.getAsString("isSetPW") != null) {
				if (aCache.getAsString("isSetPW").equals("yes")) {
					// 跳转方向1表示ReportFragment
					aCache.put("jumpDirection", "3");
					homeActivity.checkBossPW();
					return;
				}
			}
		}
		homeActivity.openSubFM(homeActivity.getOrderFm(), new FmInfo(ReportFragment.class,"营业报表", false));
	}

	/**
	 * 1:根据如果未送订单，已送订单，无效订单订单数都为0则显示昨日订单详情 2:未送订单数不为0，其他已送订单或无效订单数不为0，显示今日订单详情
	 * 3:未送订单数不为0，显示未送订单
	 */
	public void switchPanel() {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				int noSentNum = omModel.getNoSentList().size();
				int sentNum = omModel.getSentList().size();
				int invalidNum = omModel.getInvalidList().size();
				if (noSentNum == 0 && sentNum == 0 && invalidNum == 0) {
					orderFragment.noOrderView.setVisibility(View.VISIBLE);
					orderFragment.noOrderView.showNoOrderView();
				} else if (noSentNum == 0) {
					orderFragment.noOrderView.setVisibility(View.GONE);
					orderFragment.allSentView.setVisibility(View.VISIBLE);
					orderFragment.layout_order_hasorder.setVisibility(View.GONE);
					orderFragment.allSentView.showAllSendOrderView();
				} else {
					orderFragment.noOrderView.setVisibility(View.GONE);
					orderFragment.allSentView.setVisibility(View.GONE);
					orderFragment.layout_order_hasorder.setVisibility(View.VISIBLE);
				}
				orderFragment.waitPersonView.showPersonNum();
			}
		});
	}

	/**
	 * 载入所有无效订单
	 */
	public void loadInvalidOrderList() {
		executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryOrderReq queryOrderReq = new QueryOrderReq();
					queryOrderReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryOrderReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					queryOrderReq.setType(4);
					Result<QueryOrderRes> result = orderModel.queryOrderList(queryOrderReq);
					if (result != null && result.getCode() == 1 && result.getData() != null) {
						omModel.loadAllOrders(result.getData());
						refreshInvalidData();
					} else if (result != null && result.getCode() == -3) {
						homeActivity.homeController.exitLogin();
					}
				} catch (RetrofitError error) {
					switch (error.getKind()) {
					}
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 搜索订单列表数据
	 */
	public void refreshSearchData(String keyWord) {
		List<Order> allOrderList = omModel.searchOrder(keyWord);
		orderFragment.searchData.clear();
		orderFragment.searchData.addAll(allOrderList);
		orderFragment.searchOrderAdapter.notifyDataSetChanged();
	}

	/**
	 * 加载无效订单
	 */
	public void refreshInvalidData() {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				if (omModel.getInvalidList().size() > 0) {
					orderFragment.layout_order_invalid_lv.setVisibility(View.VISIBLE);
					orderFragment.invalidData.clear();
					orderFragment.invalidData.addAll(omModel.getInvalidList());
					orderFragment.invalidOrderAdapter.notifyDataSetChanged();
				}
			}
		});
	}

	/**
	 * 加载已送出页面
	 */
	public void refreshSendData() {
		// 获取已送出订单
		runOnUI(new Runnable() {
			@Override
			public void run() {
				if (omModel.getSentList().size() > 0) {
					orderFragment.layout_order_sended_lv.setVisibility(View.VISIBLE);
					orderFragment.sendData.clear();
					orderFragment.sendData.addAll(omModel.getSentList());
					orderFragment.sendedOrderAdapter.notifyDataSetChanged();
				}
			}
		});
	}

	/**
	 *  获取未送出订单
	 */
	public void refreshUnsendData() {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				orderFragment.unsendData.clear();
				orderFragment.unsendData.addAll(omModel.getNoSentList());
				orderFragment.unsendOrderAdapter.notifyDataSetChanged();
				switchPanel();
			}
		});
	}

	/**
	 * 载入所有订单
	 */
	public void loadAllOrderList() {

		executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryOrderReq queryOrderReq = new QueryOrderReq();
					queryOrderReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryOrderReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					queryOrderReq.setType(1);
					Result<QueryOrderRes> result = orderModel.queryOrderList(queryOrderReq);
					if (result != null && result.getCode() == 1 && result.getData() != null) {
						omModel.loadAllOrders(result.getData());
						refreshUnsendData();
						refreshSendData();
						refreshInvalidData();
					} else if (result != null && result.getCode() == -3) {
						homeActivity.homeController.exitLogin();
					} else {
						switchPanel();
					}
				} catch (RetrofitError error) {
					switch (error.getKind()) {
					}
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 定时刷新本地未送订单
	 */
	public void refreshLocationOrder() {
		// 关闭刷新Timer
		if (refreshTimer != null) {
			refreshTimer.cancel();
			refreshTimer = null;
		}
		if (refreshTimerTask != null) {
			refreshTimerTask.cancel();
			refreshTimerTask = null;
		}
		refreshTimer = new Timer();
		refreshTimerTask = new TimerTask() {

			@Override
			public void run() {
				runOnUI(new Runnable() {
					@Override
					public void run() {
						if (orderFragment.unsendData != null) {
							orderFragment.unsendOrderAdapter.notifyDataSetChanged();
						}
					}
				});
			}
		};
		refreshTimer.schedule(refreshTimerTask, 60 * 1000, 60 * 1000);
	}

	/**
	 * 销毁定时刷新的定时器
	 */
	public void onDestroy() {
		// 关闭刷新Timer
		if (refreshTimer != null) {
			refreshTimer.cancel();
			refreshTimer = null;
		}
		if (refreshTimerTask != null) {
			refreshTimerTask.cancel();
			refreshTimerTask = null;
		}
	}
}
